import pymysql

from FutureLoan.baw.member import register, login
from FutureLoan.caw.Log import Logger
from FutureLoan.caw.read_file import read_ini


def connect(mysqldb):
    try:
        conn = pymysql.connect(user=mysqldb["user"],  # The first four arguments is based on DB-API 2.0 recommendation.
                               password=mysqldb["pwd"],
                               host=mysqldb["host"],
                               database=mysqldb["dbname"],
                               port=mysqldb["port"],
                               charset="utf8", )
        print("数据库连接成功！")
        # Logger().info("数据库连接成功！")
        return conn
    except Exception as e:
        print(f"数据库连接异常，异常信息为：{e}")
        # Logger().error(f"数据库连接异常，异常信息为：{e}")


def close(conn):
    try:
        conn.close()
        print("断开数据库成功!")
    except Exception as e:
        print(f"断开数据库连接失败，异常信息为：{e}")
        # Logger().error(f"断开数据库连接失败，异常信息为：{e}")


def execute(conn, sql):
    try:
        c = conn.cursor()
        c.execute(sql)
        conn.commit()
        print(f"执行{sql}语句成功！")
        # Logger().info(f"执行{sql}语句成功！")
    except Exception as e:
        print(f"执行{sql}语句失败，异常信息为：{e}")
        # Logger().error(f"执行{sql}语句失败，异常信息为：{e}")


def delete_user(mysqldb, phone):
    conn = connect(mysqldb)
    execute(conn, f"DELETE FROM member WHERE mobilephone = '{phone}';")
    close(conn)


def select_userID(mysqldb, phone):
    conn = connect(mysqldb)
    c = conn.cursor()
    c.execute(f"SELECT id FROM member WHERE mobilephone = '{phone}';")
    # execute(conn, f"SELECT id FROM member WHERE mobilephone = '{phone}';")
    row = c.fetchone()
    close(conn)
    return row[0]


def delete_loan(mysqldb, data):
    conn = connect(mysqldb)
    execute(conn, f"DELETE FROM loan WHERE MemberID = '{data['memberId']}' AND Title = '{data['title']}';")
    print('删除记录成功')


if __name__ == '__main__':
    # mysqldb = {"host": "127.0.0.1", "port": 3306, "dbname": "future", "user": "root", "pwd": "123456"}

    db = eval(read_ini(r"data/env.ini", "env", "mysqldb"))
    print(select_userID(db, '18066668888'))
